#ifndef LOADERMNT_H
#define LOADERMNT_H

#include "Export.h"
#include "ILoader.h"
#include "Mesh.h"
#include <iostream>
#include <fstream>
namespace glow
{
  class SHARED LoaderMNT : public ILoader 
  {
  public :
    Mesh_data * load (string filename)
    {
      Mesh_data * Mp =new Mesh_data;
      ifstream file(_filename.c_str(), ios::in);
      int ncols, nrows, xllcorner, yllcorner, cellsize;
      float NODATA_value;
      string trash;
      float _minZ = 1000000;
      if(_filename==""){cout<<"404  file not found"<<endl; return NULL; }
      else{
	if(file){
	  file >> trash;
	  file >> ncols;
	  file >> trash;
	  file >> nrows;
	  Mp->_nb_vertices=ncols*nrows;
	  file >> trash;
	  file >> xllcorner;
	  file >> trash;
	  file >> yllcorner;
	  file >> trash;
	  file >> cellsize;
	  file >> trash;
	  file >> NODATA_value;
		
	  Mp->_vertices = new float[ncols*nrows*3];
		
	  for(int i=0; i<nrows; i++){
	    for (int j=0;j<ncols*3;j+=3){
	      // ncols*i*3+j = coord du point mais dans le tableau 1 Dimension _vertices
	      Mp->_vertices[(ncols*i*3)+j]=(i); 
	      Mp->_vertices[(ncols*i*3)+j+1]=(j/3);
	      file >> Mp->_vertices[(ncols*i*3)+j+2];
			    
	      if(Mp->_vertices[(ncols*i*3)+j+2] < _minZ && 
		 Mp->_vertices[(ncols*i*3)+j+2] != NODATA_value){ 
		_minZ = Mp->_vertices[(ncols*i*3)+j+2];
	      }
	    }
	  }
		
	  for (int a=2; a<Mp->_nb_vertices*3; a+=3){
	    if( Mp->_vertices[a] == NODATA_value ){
	      Mp->_vertices[a]=_minZ;
	    }
	  }
		
	  /* gen_index(); */
	  int ncols=sqrt(Mp->_nb_vertices);
	  int nrows=sqrt(Mp->_nb_vertices);

	  Mp->_nb_index= 2*(ncols-1)*(nrows-1);
	  Mp->_index = new unsigned int[Mp->_nb_index*3];


	  int k=0;

	  for(int i=0; i<(nrows-1); i++)
	    {
	      for (int j=1;j<(ncols);j++)
		{
		  Mp->_index[k]  = (j-1)+i*ncols;
		  k++;
		  Mp->_index[k]= (j-1)+(i+1)*ncols;
		  k++;
		  Mp->_index[k]= (j)+i*ncols;
		  k++;

		  Mp->_index[k]= (j)+i*ncols;
		  k++;
		  Mp->_index[k]= (j-1)+(i+1)*ncols;
		  k++;
		  Mp->_index[k]= (j)+(i+1)*ncols;
		  k++;
		} 	
	    } 
	  /*
	    gen_texcoord();
	  */
	  if(Mp->_nb_vertices!=0)
	    {
	      Mp->_nb_texcoord=Mp->_nb_vertices*2;
	      Mp->_texcoord =new float[Mp->_nb_texcoord];
	      int ncols=sqrt(Mp->_nb_vertices);

	      int k=0;
	      for (int i=0;i<ncols;i++)
		{
		  for (int j=0; j<ncols; j++)
		    {
		      Mp->_texcoord[k]=(float)((float)j/(ncols));
		      k++;
		      Mp->_texcoord[k]=(float)(1.-(float)i/(ncols));
		      k++;
		    }
		}    
	    }
	  else
	    {
	      cout<<"No File Loaded"<<endl;
	      return NULL;
	    }
		
		
	}
	else
	  {
	    cout<<"file loading ERROR !!!"<<endl;
	    return NULL;
	  }	
		    
      }
      return Mp;
    }
  };
}
#endif
